package sv.gob.mh.dgii.security;

import java.io.IOException;
import java.util.Date;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import sv.gob.mh.dgii.common.Utils;
import sv.gob.mh.dgii.model.DeOperacionesWeb;
import sv.gob.mh.dgii.service.cat.DeOperacionesWebService;

/**
 *
 * @author hgonzalez
 */
public class CustomAuthenticationProcessingFilter extends
		UsernamePasswordAuthenticationFilter {
	
    @Autowired
    private DeOperacionesWebService deOperacionesWebService;
    
    private void createLog(HttpServletRequest request, boolean success){
           //Long indice = deOperacionesWebService.getNextSequence();
           DeOperacionesWeb ctrlDtoLog = new DeOperacionesWeb();
           //ctrlDtoLog.setIcorrelativo(indice);
	   ctrlDtoLog.setCusuario(super.obtainUsername(request));
           ctrlDtoLog.setIpusuario(request.getRemoteAddr());
	   ctrlDtoLog.setFhioperacion(new Date());
	   ctrlDtoLog.setMoperacion("L");
           
           if(success){
               ctrlDtoLog.setFhfoperacion(new Date());
           }           
	   deOperacionesWebService.save(ctrlDtoLog);
    }
        
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
            Authentication authResult) throws IOException, ServletException{
         
        createLog(request, true);
        SscUserDetailsImpl user = (SscUserDetailsImpl)authResult.getPrincipal();
        String ctx = request.getContextPath();
        if (ctx != null && ctx.equals("/DGII")) {
            if(Utils.isNullOrEmpty(user.getBanderas()) || "11".equals(user.getBanderas())){
                if(Utils.isNullOrEmpty(user.getCtrlchgpwd())){
                    super.unsuccessfulAuthentication(request, response, 
                            new BadCredentialsException("HUBO UN ERROR DE MIGRACION CON SU USUARIO, "
                            + "POR FAVOR LLAME A NUESTRO CALL CENTER"));
                }
            }else if("00".equals(user.getBanderas()) || "10".equals(user.getBanderas())){
                if(Utils.isNullOrEmpty(user.getEmailPi())){
                    super.unsuccessfulAuthentication(request, response, 
                            new BadCredentialsException("HUBO UN ERROR DE MIGRACION CON SU USUARIO, "
                            + "POR FAVOR LLAME A NUESTRO CALL CENTER"));
                }else{
                   request.getSession().setAttribute("h0x_email", user.getEmailPi()); 
                }
            }
            
        }else{
            if("00".equals(user.getBanderas()) || "10".equals(user.getBanderas())){
                if(Utils.isNullOrEmpty(user.getEmailServ())){
                    super.unsuccessfulAuthentication(request, response, 
                            new BadCredentialsException("HUBO UN ERROR DE MIGRACION CON SU USUARIO, "
                            + "POR FAVOR LLAME A NUESTRO CALL CENTER"));
                }else{
                    request.getSession().setAttribute("h0x_email", user.getEmailServ()); 
                }
                
            }
        }
        
        request.getSession().setAttribute("h0x_force", user.getCtrlchgpwd());
        
        super.successfulAuthentication(request, response, chain, authResult);
    }
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException failed) throws IOException, ServletException {                
        createLog(request, false);
        super.unsuccessfulAuthentication(request, response, failed);
    }
        
}